package com.lightbook.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.lightbook.pojo.Book;
import com.lightbook.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

//    @ResponseBody
//    @GetMapping("/select/book")
//    public String book(Book book) throws JsonProcessingException {
//        Page<Book> pageNum = new Page<>(1, 15);
//        /*List<Book> list = bookService.list(null);*/
//        /*list.forEach(System.out::println);*/
//        String key="book:"+1+":"+15;
//        String jsonBook = stringRedisTemplate.opsForValue().get(key);
//        if(StrUtil.isNotBlank(jsonBook)){
//            return jsonBook;
//        }
//        IPage<Book> bookIPage = bookService.selectPage(pageNum, book);
//        ObjectMapper objectMapper = new ObjectMapper();
//        String strBook = objectMapper.writeValueAsString(bookIPage);
//        stringRedisTemplate.opsForValue().set(key, strBook,30L, TimeUnit.MINUTES);
//        return strBook;
//
//    }

    @ResponseBody
    @GetMapping("/select/book/{page}/{limit}")
    public String book(@PathVariable Integer page,
                      @PathVariable Integer limit,
                      Book book) {
        Page<Book> pageNum = new Page<>(page, limit);

        String key="book:"+page+":"+limit;
        String jsonBook = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(jsonBook)){
            return jsonBook;
        }
        IPage<Book> bookIPage = bookService.selectPage(pageNum, book);
        ObjectMapper objectMapper = new ObjectMapper();
        String strBook = null;
        try {
            strBook = objectMapper.writeValueAsString(bookIPage);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        stringRedisTemplate.opsForValue().set(key, strBook,30L, TimeUnit.MINUTES);
        return strBook;
    }
}
